package com.kyrie.lib_sys.context;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 基于threadlocal的获取用户应用上下文
 *
 * @author heefM
 * @date 2025-09-04
 */
public class RequestHolder {
    private static final ThreadLocal<String> USER_HOLDER = new ThreadLocal<>();
    
    /**
     * 设置当前用户
     * @param username 用户名
     */
    public static void setCurrentUser(String username) {
        USER_HOLDER.set(username);
    }
    
    /**
     * 获取当前用户
     * @return 当前用户名
     */
    public static String getCurrentUser() {
        return USER_HOLDER.get();
    }
    
    /**
     * 清除当前用户信息
     */
    public static void clear() {
        USER_HOLDER.remove();
    }
    
    /**
     * 获取当前请求信息
     * @return HttpServletRequest对象
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }

}
